package com.wn.common.utils

import androidx.core.net.toUri
import okhttp3.Interceptor
import okhttp3.Response

/**
 * @Author: wn
 * @Date: 2023/2/8 16:51
 * @Description: 用于调试开发期间，替换 baseHost的拦截器
 */
class HostInterceptor : Interceptor {

  override fun intercept(chain: Interceptor.Chain): Response {
    val originRequest = chain.request()
    val oldHost = originRequest.url.host // https://release.course.api.cniao5.com/ 不带 scheme的
    val oldUrlStr = originRequest.url.toString() // fullPath
    // 调试使用
    val newHost = getBaseHost().toUri().host ?: oldHost

    val newUrlStr =
      if (newHost == oldHost)
        oldUrlStr
      else
        oldUrlStr.replace(oldHost, newHost) // 返回一个新字符串，通过将该字符串中所有出现的oldValue子字符串替换为指定的newValue字符串获得
    val newBuilder = originRequest.newBuilder()
//        LogUtils.i("Host 拦截器 ${originRequest.url} 拦截后 $newUrlStr")
    newBuilder.url(newUrlStr)
    return chain.proceed(newBuilder.build())
  }

}